package com.work.leecode.string.middle;

import java.util.HashMap;

/**
 * 无重复字符的最长子串---3
 */
public class Lc3 {

    //滑动窗口（双指针）
    public int lengthOfLongestSubstring(String s) {
        if (s == null || s.isEmpty()) {
            return 0;
        }
        int left = 0, max = 0;
        HashMap<Character, Integer> map = new HashMap<>();
        for (int right = 0; right < s.length(); right++) {
            char c = s.charAt(right);
            if (map.containsKey(c)) {
                left = Math.max(map.get(c) + 1, left);
            }
            map.put(c, right);
            max = Math.max(right - left + 1, max);
        }
        return max;
    }

    //复习2024.05.05
    //双指针
    public int lengthOfLongestSubstring2(String s) {
        if (s == null || s.isEmpty()) {
            return 0;
        }

        HashMap<Character, Integer> map = new HashMap<>();
        int left = 0;
        int maxLen = Integer.MIN_VALUE;

        char[] arr = s.toCharArray();
        for (int right = 0; right < arr.length; right++) {
            if (map.containsKey(arr[right])) {
                left = Math.max(left, map.get(arr[right]) + 1);
            }
            map.put(arr[right], right);
            maxLen = Math.max(maxLen, right - left + 1);
        }
        return maxLen;
    }
}
